package xcmg.device.service.ratingManager;

import com.github.pagehelper.PageInfo;
import yb.ecp.fast.infra.util.PageHelperPlus;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xcmg.device.dao.entity.company.CompanyDealerDO;
import xcmg.device.dao.entity.company.DealerClassDO;
import xcmg.device.dao.entity.ratingManager.CompleteRateConfigDO;
import xcmg.device.dao.mapper.CompanyDealerMapper;
import xcmg.device.dao.mapper.DealerClassMapper;
import xcmg.device.dao.mapper.ratingManager.CompleteRateConfigDOMapper;
import xcmg.device.infra.ErrorCode;
import xcmg.device.infra.ExcelUtil;
import xcmg.device.infra.FileUtil;
import xcmg.device.service.vo.FunctionResult;
import xcmg.device.service.vo.ratingManager.BasisQueryVO;
import xcmg.device.service.vo.ratingManager.CompleteRateConfigVO;
import yb.ecp.fast.feign.FastGenClient;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;
import yb.ecp.fast.infra.util.StringUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by wrg on 2019/7/10.
 */
@Service
public class CompleteRateConfigService {
    @Autowired
    private CompleteRateConfigDOMapper completeRateConfigDOMapper;

    @Autowired
    private FastGenClient genClient;
    @Value("${spring.file.download.path}")
    private String filePath;
    private String templateExcelFileName = "CompleteRateConfig.xls";
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private CompanyDealerMapper companyDealerMapper;
    @Autowired
    private DealerClassMapper dealerClassMapper;

    private String AGENT_TYPE = "常规代理商";

    @Transactional(rollbackFor = Exception.class)
    public ErrorCode add(CompleteRateConfigVO completeRateConfigVO) throws Exception {
        CompleteRateConfigDO record = new CompleteRateConfigDO();
        BeanUtils.copyProperties(completeRateConfigVO, record);
        ErrorCode errorCode = checkAddData(completeRateConfigVO);
        if (errorCode != null) {
            return errorCode;
        }

        String id = genClient.newGuidText().getValue();
        if (StringUtils.isBlank(id)) {
            return ErrorCode.IllegalArument;
        }
        record.setId(id);
        record.setCreateTime(new Date());
        return completeRateConfigDOMapper.insertSelective(record) > 0 ? ErrorCode.Success : ErrorCode.Failure;
    }

    private ErrorCode checkAddData(CompleteRateConfigVO completeRateConfigVO) {
        CompanyDealerDO companyDealerDO = companyDealerMapper.item(Long.valueOf(completeRateConfigVO.getClientId()));
        if (companyDealerDO == null) {
            return ErrorCode.DealerInfoNotExist;
        }
        Long dealerClassId = companyDealerDO.getDealerClassId();
        if (null == dealerClassId) {
            return ErrorCode.CustomerNotRegularAgent;
        }

        DealerClassDO dealerClassDO = dealerClassMapper.item(dealerClassId);
        if (null == dealerClassDO || !dealerClassDO.getClassName().equals(AGENT_TYPE)) {
            return ErrorCode.CustomerNotRegularAgent;
        }
        int count = completeRateConfigDOMapper.countByRatingIdClientId(completeRateConfigVO.getRatingId(), String.valueOf(companyDealerDO.getId()));
        if (count > 0) {
            return ErrorCode.CustomerInfoAlreadyExists;
        }
        return null;
    }

    @Transactional(rollbackFor = Exception.class)
    public ErrorCode remove(List<String> ids) throws Exception {
        for (String id : ids) {
            int deleteCount = completeRateConfigDOMapper.deleteByPrimaryKey(id);
            if (deleteCount <= 0) {
                throw new Exception("删除失败");
            }
        }

        return ErrorCode.Success;
    }


    @Transactional(rollbackFor = Exception.class)
    public ErrorCode update(CompleteRateConfigVO completeRateConfigVO) throws Exception {
        CompleteRateConfigDO record = new CompleteRateConfigDO();
        BeanUtils.copyProperties(completeRateConfigVO, record);
        record.setModifyTime(new Date());
        return completeRateConfigDOMapper.updateByPrimaryKeySelective(record) > 0 ? ErrorCode.Success : ErrorCode.Failure;
    }

    public PageCommonVO list(SearchCommonVO<BasisQueryVO> condition) {
        PageHelperPlus.orderBy("create_time,id desc");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
        List<CompleteRateConfigDO> doList = completeRateConfigDOMapper.selectByRatingId(condition.getFilters());
        List<CompleteRateConfigVO> voList = new ArrayList<>();
        for (CompleteRateConfigDO completeRateConfigDO : doList) {
            CompleteRateConfigVO completeRateConfigVO = new CompleteRateConfigVO();
            BeanUtils.copyProperties(completeRateConfigDO, completeRateConfigVO);
            voList.add(completeRateConfigVO);
        }
        PageCommonVO<CompleteRateConfigVO> result = new PageCommonVO<>();
        result.setPageInfo(new PageInfo<>(doList));
        result.setPageInfoList(voList);
        return result;
    }

    public CompleteRateConfigVO item(String id) {
        CompleteRateConfigDO completeRateConfigDO = completeRateConfigDOMapper.selectByPrimaryKey(id);
        CompleteRateConfigVO completeRateConfigVO = new CompleteRateConfigVO();
        if (null != completeRateConfigDO) {
            BeanUtils.copyProperties(completeRateConfigDO, completeRateConfigVO);
        }
        return completeRateConfigVO;
    }

    public void download() throws Exception {
        FileUtil.downLoadFile(response, filePath, templateExcelFileName);
    }


    public FunctionResult importExcel(InputStream in, String ratingId, String userId, String userName, String orgId) throws Exception {
        FunctionResult result = new FunctionResult();
        HSSFWorkbook wb = new HSSFWorkbook(in);
        HSSFSheet sheet = wb.getSheetAt(0);
        int totalRow = sheet.getLastRowNum();
        if (totalRow < 2) {
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("导入模板不正确");
            return result;
        }
        int totalCell = sheet.getRow(2).getLastCellNum();
        if (totalCell != 5) {
            result.setCode(ErrorCode.IllegalArument);
            result.setValue("导入模板不正确");
            return result;
        }

        List<CompleteRateConfigVO> errorDetailVOList = new ArrayList<>();
        boolean success;
        for (int i = 2; i <= totalRow; i++) {
            HSSFRow curRow = sheet.getRow(i);
            CompleteRateConfigVO completeRateConfigVO = new CompleteRateConfigVO();
            if (curRow == null) {
                continue;
            }
            if (isRowEmpty(curRow)) {
                continue;
            }

            String totalSalesTarget = excelValue(curRow, 3);
            if (checkFormat(errorDetailVOList, i, completeRateConfigVO, totalSalesTarget)) {
                continue;
            }

            String clientNo = excelValue(curRow, 1);
            CompanyDealerDO companyDealerDO = companyDealerMapper.itemByDealerCode(orgId, clientNo);
            if (companyDealerDO == null) {
                completeRateConfigVO.setErrorRow(i + 1);
                completeRateConfigVO.setRemark("客户信息不存在");
                errorDetailVOList.add(completeRateConfigVO);
                continue;
            }
            Long dealerClassId = companyDealerDO.getDealerClassId();
            if (null == dealerClassId) {
                completeRateConfigVO.setErrorRow(i + 1);
                completeRateConfigVO.setRemark("客户不是常规代理商");
                errorDetailVOList.add(completeRateConfigVO);
                continue;
            }
            DealerClassDO dealerClassDO = dealerClassMapper.item(dealerClassId);
            if (null == dealerClassDO || !dealerClassDO.getClassName().equals(AGENT_TYPE)) {
                completeRateConfigVO.setErrorRow(i + 1);
                completeRateConfigVO.setRemark("客户不是常规代理商");
                errorDetailVOList.add(completeRateConfigVO);
                continue;
            }

            int count = completeRateConfigDOMapper.countByRatingIdClientId(ratingId, String.valueOf(companyDealerDO.getId()));
            if (count > 0) {
                completeRateConfigVO.setErrorRow(i + 1);
                completeRateConfigVO.setRemark("客户信息已存在");
                errorDetailVOList.add(completeRateConfigVO);
                continue;
            }

            CompleteRateConfigDO record = new CompleteRateConfigDO();
            record.setRatingId(ratingId);
            record.setClientId(String.valueOf(companyDealerDO.getId()));
            record.setClientName(companyDealerDO.getCompanyName());
            record.setCreateTime(new Date());
            record.setCreatorId(userId);
            record.setCreatorName(userName);
            record.setTotalSalesTarget(new BigDecimal(totalSalesTarget));
            record.setRemark(excelValue(curRow, 4));
            String id = genClient.newGuidText().getValue();
            if (StringUtils.isBlank(id)) {
                completeRateConfigVO.setErrorRow(i + 1);
                completeRateConfigVO.setRemark("主键生成失败");
                errorDetailVOList.add(completeRateConfigVO);
                continue;
            }
            record.setId(id);
            success = completeRateConfigDOMapper.insertSelective(record)>0;
            if (!success) {
                completeRateConfigVO.setErrorRow(i + 1);
                completeRateConfigVO.setRemark("销售完成率配置失败，客户编码：" + clientNo);
                errorDetailVOList.add(completeRateConfigVO);
            }
        }

        AccountOverdueConfigService.getImportResult(result, errorDetailVOList);
        return result;
    }

    private boolean checkFormat(List<CompleteRateConfigVO> errorDetailVOList, int i, CompleteRateConfigVO completeRateConfigVO, String totalSalesTarget) {
        if (!isInteger(totalSalesTarget)) {
            completeRateConfigVO.setErrorRow(i + 1);
            completeRateConfigVO.setRemark("总销售目标格式不正确");
            errorDetailVOList.add(completeRateConfigVO);
            return true;
        }
        if (new BigDecimal(totalSalesTarget).compareTo(BigDecimal.valueOf(9999999999.99)) > 0) {
            completeRateConfigVO.setErrorRow(i + 1);
            completeRateConfigVO.setRemark("总销售目标过大");
            errorDetailVOList.add(completeRateConfigVO);
            return true;
        }
        return false;
    }

    private String excelValue(HSSFRow curRow, Integer line) {
        Cell cell = curRow.getCell(line);
        String cellValue = "";
        if (null != cell) {
            // 以下是判断数据的类型
            switch (cell.getCellType()) {
                case HSSFCell.CELL_TYPE_NUMERIC: // 数字
                    DecimalFormat df = new DecimalFormat("0");
                    cellValue = df.format(cell.getNumericCellValue());
                    break;

                case HSSFCell.CELL_TYPE_STRING: // 字符串
                    cellValue = cell.getStringCellValue();
                    break;

                case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
                    cellValue = cell.getBooleanCellValue() + "";
                    break;

                case HSSFCell.CELL_TYPE_FORMULA: // 公式
                    cellValue = cell.getCellFormula() + "";
                    break;

                case HSSFCell.CELL_TYPE_BLANK: // 空值
                    cellValue = "";
                    break;

                case HSSFCell.CELL_TYPE_ERROR: // 故障
                    cellValue = "";
                    break;

                default:
                    cellValue = "";
                    break;
            }
        }
        return cellValue;
    }

    public static boolean isRowEmpty(HSSFRow row) {
        for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {
            HSSFCell cell = row.getCell(c);
            if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK && !StringUtil.isNullOrSpace(ExcelUtil.getCellStringValue(cell))) {
                return false;
            }
        }
        return true;
    }

    private boolean isInteger(String str) {
        if (null == str || "".equals(str)) {
            return false;
        }
        try {
            BigDecimal decimal = new BigDecimal(str);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

}
